#include <iostream>
#include <pthread.h>
#include "UdpServer.hpp"
#include "Log.hpp"

using namespace std;

struct ThreadDate
{
    struct sockaddr_in server;
    int sockfd;
};

//这里的Please Enter@会和接受到的消息混合在一起, 导致看起来很不舒服, 也就是输入和输入混到一起了
//我们可以使用多个终端来避免这个问题 -> ./UdpClient serverip serverport 2>/dev/pts/你想要的终端号（num）
void *send_message(void *args)
{
    ThreadDate *td = static_cast<ThreadDate *>(args);
    socklen_t len = sizeof(td->server);

    string message;

    while (true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);

        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}

void *recv_message(void *args)
{
    ThreadDate *td = static_cast<ThreadDate *>(args);

    char buffer[1024];

    while (true)
    {
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);

        int n = recvfrom(td->sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&tmp, &len);
        if (n > 0)
        {
            buffer[n] = '\0';
            cerr << buffer << endl;
        }
    }
}

// 客户端需要给他设置成为多线程, 否则如果用户不发送就无法接受服务器给他转发的消息
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Please Enter: ./exe serverip serverport" << endl;
        return 1;
    }

    string serverip = argv[1];
    uint16_t serverport = htons(stoi(argv[2]));

    ThreadDate td;
    memset(&td.server, 0, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = serverport;
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        perror("create socket fail\n");
        return 2;
    }

    pthread_t recvr, sender;
    //线程里面需要的参数可以通过这个函数传进去, 如果需要多个参数, 可以通过封装类的方式一起传递
    pthread_create(&sender, nullptr, send_message, &td);
    pthread_create(&recvr, nullptr, recv_message, &td);

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    return 0;
}